package bin_tree.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author yuisama
 * @date 2023/03/27 18:56
 * 前序遍历
 **/
public class Num144_PreOrder {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        // 当栈为空，所有节点访问完毕
        while (!stack.isEmpty()) {
            // 根
            TreeNode node = stack.pop();
            result.add(node.val);
            // 先压入右子树
            if (node.right != null) {
                stack.push(node.right);
            }
            // 再压入左子树
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return result;
    }
}